package cn.xaut.查找表;

import java.util.HashSet;
import java.util.Set;

public class demo202 {

    private int getNext(int n) {

        int res = 0;
        while (n > 0) {
            res += Math.pow(n % 10, 2);
            n /= 10;
        }
        return res;
    }

    // 快慢指针法
    public boolean isHappy2(int n) {
        
        int slow = n;
        int fast = getNext(n);
        while (fast != 1 && slow != fast) {
            slow = getNext(slow);
            fast = getNext(getNext(fast));
        }
        return fast == 1;
    }
    
    // 集合法
    public boolean isHappy(int n) {

        Set<Integer> set = new HashSet<>();
        while (n != 1) {
            if (!set.add(n))
                return false;
            n = getNext(n);
        }
        return true;
    }

    public static void main(String[] args) {

        System.out.println(new demo202().isHappy2(19));//true
        System.out.println(new demo202().isHappy2(2));//false
    }
}
